package com.ciwong.epaper.modules.viedoexplantion.player;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.frank.ffmpeg.handler.FFmpegHandler;
import com.frank.ffmpeg.util.FFmpegUtil;

import java.io.File;
import java.util.UUID;

import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_BEGIN;
import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_FINISH;
import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_PROGRESS;

/**
 * khbvod播放器
 */
public class KHBVideoPlayActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "KHBVideoPlayActivity";
    private String oldVideoPath = "/storage/emulated/0/dubing/video/0db0afa87d8361051a43622d7d433372_play";
    private String oldVideoUrl = "http://rimg3.ciwong.net/6v68/tools/images/401217/111bf29c36d7bdc5336e4e6bba60cba41d6a0d2c.png";
    private String outVideoPath = ESystem.getDubingVideoPath() + File.separator + "video.mp4";
    private String videoAudioPath = ESystem.getDubingVideoPath() + File.separator + "videoMusicAudio.mp4";
    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;
    private Button play_mode_mute_bt, play_mode_unmute_bt, play_mode_unmute_recode_bt, finish_unmute_recode_bt;
    /**
     * 录音
     */
    protected Mp3Recorder mp3Recorder;
    //做题记录
    protected String uuid = UUID.randomUUID().toString();
    /**
     * 录音路径
     */
    private String mRecorderPath;
    /**
     * 录音图标
     */
    private ImageView img_micro_recording;
    /**
     * 录音分贝
     */
    private double mVolume = -1.0;
    /**
     * 是否录制失败
     */
    protected boolean isRecordFail = false;
    /**
     * 录制时长
     */
    protected int recordTime = 15;

    private Handler mRecorderHandler = new Handler(Looper.myLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                    img_micro_recording.setVisibility(View.VISIBLE);
                    Drawable drawable = img_micro_recording.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable).start();
                    }

                    break;
                case Mp3Recorder.MSG_DB:// 录音分贝
                    Bundle b = msg.getData();
//                    CWLog.d(TAG, "###########Mp3Recorder.MSG_DB############" + Mp3Recorder.MSG_DB);
                    if (b != null) {
                        double db = b.getDouble("db");
                        if (db >= 0) {
                            CWLog.d(TAG, "###########db############" + db);
                            mVolume = db;
                        }
//                        CWLog.d(TAG, "###########db############" + db);

//                        if (microRecording != null && !Double.isNaN(db)) {
//                            microRecording.setRms(db);
//                        }
                    }
                    break;
                case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                    isRecordFail = true;
                    CWLog.d(TAG, "###########Mp3Recorder.MSG_ERROR_AUDIO_RECORD############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    DialogUtil.showSettingPermissions(KHBVideoPlayActivity.this);
                    break;

                case Mp3Recorder.MSG_ERROR_REC_START:
                    isRecordFail = true;
                    CWLog.d(TAG, "###########Mp3Recorder.MSG_ERROR_REC_START############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);

                    DialogUtil.showSettingPermissions(KHBVideoPlayActivity.this);
                    break;
                case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                    img_micro_recording.setVisibility(View.GONE);
                    Drawable drawable2 = img_micro_recording.getDrawable();
                    if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable2).stop();
                    }
                    cutSelectMusic(mRecorderPath);
                    break;
                default:
                    break;
            }
        }

    };
    private int int_ffmpeg = 0;
    private String downloadMsg = "视频处理中...";
    private FFmpegHandler ffmpegHandler;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_BEGIN:
                    showDownloadProgress(downloadMsg);
                    break;
                case MSG_FINISH:
                    hideDownloadProgress();
                    if (int_ffmpeg == 1) {
                        //处理静音
                        Toast.makeText(KHBVideoPlayActivity.this, "extractAudio ffmpeg end...", Toast.LENGTH_SHORT).show();
                    } else if (int_ffmpeg == 2) {
                        //合成配音
                        Toast.makeText(KHBVideoPlayActivity.this, "concatAudio ffmpeg end...", Toast.LENGTH_SHORT).show();
                    } else if (int_ffmpeg == 3) {
                        //合成配音
                        mKHBVideoPlayerStandard.setplsyModeUp(outVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_NORMAL, KHBVideoPlayer.PLAY_MODE_MUTE, "");
                        mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
                    } else if (int_ffmpeg == 4) {
                        //合成配音
                        composeMusicAndAudio(mRecorderPath);
                    } else if (int_ffmpeg == 5) {
                        //合成配音
                        mKHBVideoPlayerStandard.setplsyModeUp(videoAudioPath, KHBVideoPlayer.SCREEN_LAYOUT_NORMAL, KHBVideoPlayer.PLAY_MODE_MUTE, "");
                        mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
                    }
                    int_ffmpeg = 0;
                    break;
                case MSG_PROGRESS:
                    int progress = msg.arg1;
                    int duration = msg.arg2;
                    if (progress > 0) {
                        updateDownloadProgress(progress);
                    } else {
                        hideDownloadProgress();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    protected void initData() {
        Intent intent = getIntent();
        oldVideoPath = intent.getStringExtra(IntentFlag.INTENT_FLAG_OBJ);
        initView();
    }

    private void initView() {
    }

    @Override
    protected int setView() {
        return R.layout.activity_khb_video_play;
    }

    @Override
    protected void findViews() {
        setTitleText("播放视频");
        mKHBVideoPlayerStandard = findViewById(R.id.khb_content_video);
        play_mode_mute_bt = findViewById(R.id.play_mode_mute_bt);
        play_mode_unmute_bt = findViewById(R.id.play_mode_unmute_bt);
        play_mode_unmute_recode_bt = findViewById(R.id.play_mode_unmute_recode_bt);
        finish_unmute_recode_bt = findViewById(R.id.finish_unmute_recode_bt);
        img_micro_recording = findViewById(R.id.img_micro_recording);
    }

    @Override
    protected void initEvent() {
        play_mode_mute_bt.setOnClickListener(this);
        play_mode_unmute_bt.setOnClickListener(this);
        play_mode_unmute_recode_bt.setOnClickListener(this);
        finish_unmute_recode_bt.setOnClickListener(this);
    }

    @Override
    protected void init() {
        ffmpegHandler = new FFmpegHandler(mHandler);
        initData();
        mKHBVideoPlayerStandard.setplsyModeUrlUp(oldVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView, oldVideoUrl);
        recordTime = mKHBVideoPlayerStandard.getDuration() > 0 ? mKHBVideoPlayerStandard.getDuration() : 15;
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
                    break;
            }
        } else {
            if (requestCode == RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY) {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.play_mode_mute_bt) {
            //静音播放
            extractVideo(oldVideoPath);
        } else if (i == R.id.play_mode_unmute_bt) {
            //有声播放
//            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
            concatAudio();
        } else if (i == R.id.play_mode_unmute_recode_bt) {
            //静音播放并开始录音
            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_MUTE);
            startRecord();
        } else if (i == R.id.finish_unmute_recode_bt) {
            //结束录音
//            KHBVideoPlayer.releaseAllVideos();
//            mp3Recorder.stop();
            composeMusicAndAudio(mRecorderPath);
        }
    }

    /**
     * 开始录音
     */
    private void startRecord() {
        CWLog.d(TAG, "开始录音");
        //得到音频保存地址
        mRecorderPath = ESystem.getDubingVideoPath() + File.separator + System.currentTimeMillis() + EConstants.AUDIO_DEFAULT_SUFFIX;
        mp3Recorder = new Mp3Recorder(mRecorderPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.start();
    }

    /**
     * 提取单独的视频，没有声音
     */
    private void extractAudio(String inVideoPath) {
        mRecorderPath = outVideoPath + "all.m4a";
        String[] commands = FFmpegUtil.extractAudio(inVideoPath, mRecorderPath);
        if (ffmpegHandler != null) {
            int_ffmpeg = 1;
            downloadMsg = "extractAudio ffmpeg start...";
            ffmpegHandler.executeFFmpegCmd(commands);
        }
    }

    /**
     * 提取单独的视频，没有声音
     */
    private void concatAudio() {
        mRecorderPath = outVideoPath + "all.m4a";
        String[] commands = new String[7];
        commands[0] = "ffmpeg";
        commands[1] = "-y";
        commands[0] = "-i";
        commands[0] = "concat:" + mRecorderPath + "|storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5067588872915509750/3a98fa8e-ad2e-49bb-acdc-52ab59989fce/5d16972613fd121b7610c2e844330b31.mp3";
        commands[0] = "-acodec";
        commands[0] = "copy";
        commands[0] = outVideoPath + "all22.m4a";
        if (ffmpegHandler != null) {
            int_ffmpeg = 2;
            downloadMsg = "concatAudio ffmpeg start...";
            ffmpegHandler.executeFFmpegCmd(commands);
        }
    }

    /**
     * 提取单独的视频，没有声音
     */
    private void extractVideo(String inVideoPath) {
        String[] commands = FFmpegUtil.extractVideo(inVideoPath, outVideoPath);
        if (ffmpegHandler != null) {
            int_ffmpeg = 3;
            downloadMsg = "extractVideo ffmpeg start...";
            ffmpegHandler.executeFFmpegCmd(commands);
        }
    }

    /**
     * 处理录音音频
     *
     * @param musicUrl
     */
    private void cutSelectMusic(String musicUrl) {
        final String musicPath = ESystem.getDubingVideoPath() + File.separator + "bgMusic.aac";
        int time = mKHBVideoPlayerStandard.getDuration() > 0 ? mKHBVideoPlayerStandard.getDuration() : 15;
        String[] commands = FFmpegUtil.cutAudio(musicUrl, 0, time, musicPath);
        if (ffmpegHandler != null) {
            int_ffmpeg = 4;
            downloadMsg = "cutSelectMusic ffmpeg start...";
            ffmpegHandler.executeFFmpegCmd(commands);
        }
    }

    /**
     * 视频和背景音乐合成
     *
     * @param bgMusicAndAudio
     */
    private void composeMusicAndAudio(String bgMusicAndAudio) {
        final String videoUrl = oldVideoPath;
        String[] commands = FFmpegUtil.mixAudioAndVideo(videoUrl, bgMusicAndAudio, videoAudioPath);
        if (ffmpegHandler != null) {
            int_ffmpeg = 5;
            downloadMsg = "视频和背景音乐开始合成！！";
            ffmpegHandler.executeFFmpegCmd(commands);
        }
    }

    private void showProgressLoading() {
        showCricleProgress();
    }

    private void dismissProgress() {
        hideCricleProgress();
    }
}